import _ from 'lodash'
import customLoadmore from '@/components/common/custom-loadmore.vue'
import customSearch from '@/components/common/custom-search.vue'
import customPopCheckbox from '@/components/common/custom-pop-checkbox.vue'
import customTimer from '@/components/common/custom-timer.vue'
import customPopCascade from '@/components/common/custom-pop-cascade.vue'
import GetSelect from '@/assets/mixin/getSelect'
import { downloadAttachment, exportFile, getFileExtension } from '@/utils'
import { mapMutations } from 'vuex'
import { Base64 } from 'js-base64'
import { Toast } from 'vant'

export default {
  components: {
    customLoadmore,
    customSearch,
    customPopCheckbox,
    customTimer,
    customPopCascade
  },
  mixins: [GetSelect],
  inject: ['layout', 'excludeCache'],
  data() {
    return {
      total: 0,
      pages: 0,
      currentType: "",
      superSearch: false
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.meta.level !== 4) {
      this.excludeCache(from)
    }
    next()
  },
  created() {
    this.currentType = this.$route.query.current
  },
  methods: {
    ...mapMutations({
      refreshList: 'refresh/SET_REFRESH'
    }),
    // 打开高级查询弹窗
    openSuperSearch() {
      this.superSearch = true
    },
    // 点击防抖
    handleClick: _.debounce((resolve) => {
      typeof resolve === 'function' && resolve()
    }, 200),
    // 导出
    handleExport: _.debounce((url, params, fileName) => {
      exportFile(url, params, fileName)
    }, 500),
    // 下载
    handleDownLoad: _.debounce((attachUuid) => {
      downloadAttachment({ attachUuid: attachUuid })
    }, 500),
    // 打开附件弹窗
    openAttachPopUp(attachList, refName = 'attachPopUp') {
      console.log('attachList',attachList)
      this.$refs[refName].attachPopUp = true
      this.$refs[refName].attachList = attachList
    },
    // 附件上传删除回调
    uploadCallback(item, formName, uploadName, fieldName) {
      const attachIdList = this.$refs[uploadName].upLoadFileList.map((x) => {
        return x.attachId;
      });
      this[formName][fieldName] = attachIdList.toString();
      this.$refs[formName].validateField(fieldName);
    },
    setLegend(chart,myChart,params = {}){
      const nextEle = chart.nextElementSibling
      if(nextEle && nextEle.className.split(' ').includes('start--mark--legend-self--end')){
        nextEle.parentElement.removeChild(nextEle)
      }
      const legendOption = {
        icon:params.icon||'roundRect' // roundRect、circle、none
      }
      const options = myChart.getOption()
      let data = []
      if (options.series.length > 1) {
        data = options.series.map(val => ({
          name: val.name,
          color: val.itemStyle.color
        }))
      } else {
        data = options.series[0].data.map((val,index) => ({
          name: val.name,
          color: val.itemStyle?val.itemStyle.color:options.color[index]
        }))
      }
      const legendNode = document.createElement('div')
      legendNode.className = 'legend-self start--mark--legend-self--end'
      legendNode.innerHTML = `
        <div class="legend-self-list">
          ${data.map(val =>
        `
                <div class="legend-self-item">
                  <span class="${legendOption.icon}" style="--legendColor:${val.color}"></span>
                  <span class="name">${val.name}</span>
                </div>
              `
      ).join('')}
        </div>
      `
      chart.insertAdjacentElement('afterend', legendNode)
      // chart.parentNode.appendChild(legendNode)
    },
    /**
     * 预览：会新开一个窗口
     * @param {url} string 完整文件下载地址(可以直接在地址栏输入该地址，下载该文件)
     * @param {fileName} string 完整文件名称（需要带上文件后缀，用来解析是什么类型的文件，会显示在新开窗口的标题栏）
     */
    handlePreview(url, fileName) {
      debugger
      console.log(url, fileName);
      // 根据fileName 判断是否是MP4，MP3 还是其他文件
      const fileExtension = getFileExtension(fileName);
      const isVideo = fileExtension === 'mp4' || fileExtension === 'mp3' ||  fileExtension === 'MP4' || fileExtension === 'MP3';
      const isNotPreview = fileExtension === 'rar' || fileExtension === 'zip' || fileExtension === 'bmp' || fileExtension === 'eml' || fileExtension === 'RAR' || fileExtension === 'ZIP' || fileExtension === 'BMP' || fileExtension === 'EML';

      if (isVideo){
        const previewUrl=`video.html?param1=${fileName}&param2=${url}`
        window.open(previewUrl)
      } else if(isNotPreview){
        Toast.fail('该类型附件无法预览')
        this.handleDownLoad(url)
      } else if(fileExtension==='xlsx') {
        const baseUrl = `${url}&fullfilename=${fileName}&officePreviewType=${fileExtension}`;
        if (baseUrl) {
          const isFormal =window.location.href.indexOf("ahgl.csgc.com.cn") > -1? "https://ahjk.csgc.com.cn:8012" : "http://bz.eecn.top:8012";
          window.open(
            isFormal +`/onlinePreview?url=` + encodeURIComponent(Base64.encode(baseUrl))
          );
        } else {
          Toast.fail('暂无附件！')
        }
      } else {
        const baseUrl = `${url}&fullfilename=${fileName}&officePreviewType=${fileExtension}`;
        if (baseUrl) {
          const isFormal =
            window.location.href.indexOf("ahgl.csgc.com.cn") > -1
              ? "https://ahjk.csgc.com.cn:8012"
              : "http://bz.eecn.top:8012";
          console.log()
          window.open(
            isFormal +
            "/onlinePreview?url=" +
            encodeURIComponent(Base64.encode(baseUrl))+`&officePreviewType=${fileExtension}`
          );
        } else {
          Toast.fail('暂无附件！')
        }
      }
    },

    /**
     * 使用_.cloneDeep克隆一份formData，通过Object.keys遍历重新赋值 字符串默认''
     * @param {Object} formData form数据
     * @param {Object} config 传入配置 默认为{}
     * @param {Array} config.arrayResetKeys 需要将值换成[]的keys数组集合
     * @param {Array} config.ObjectResetKeys 需要将值换成{}的keys数组集合
     * @param {Array} config.ignoreKeys 需要忽略重置的keys数组集合
     * @returns {Object} 替换用的form数据
     */
    resetFormData: (formData, config = {}) => {
      // 默认配置
      const defaultConfig = {
        arrayResetKeys: [],
        ObjectResetKeys: [],
        ignoreKeys: [],
      };
      // 合并配置
      const mergedConfig = { ...defaultConfig, ...config };

      const formDataReturn = _.cloneDeep(formData);
      Object.keys(formDataReturn).forEach((v) => {
        if (mergedConfig.arrayResetKeys.includes(v)) {
          formDataReturn[v] = [];
        } else if (mergedConfig.ObjectResetKeys.includes(v)) {
          formDataReturn[v] = {};
        } else if (mergedConfig.ignoreKeys.includes(v)) {
          formDataReturn[v] = formDataReturn[v];
        } else {
          formDataReturn[v] = "";
        }
      });
      return formDataReturn;
    }
  }
}
